import json

from django import http
from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
# Create your views here.
from apps.goods.models import SKU
from utils.cookiesecret import CookieSecret


class CartsSimpleView(View):
    """商品页面右上角购物车"""

    def get(self, request):
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，查询Redis购物车
            carts_redis_client = get_redis_connection('carts')
            carts_data = carts_redis_client.hgetall(user.id)
            # 转换格式
            cart_dict = {int(key.decode()): json.loads(value.decode()) for key,value in carts_data.items()}
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })

        # 响应json列表数据
        return http.JsonResponse({'code': '0', 'errmsg': 'OK', 'cart_skus': cart_skus})


class CartsSelectAllView(View):
    """全选购物车"""

    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)
        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            carts_redis_client = get_redis_connection('carts')
            carts_data = carts_redis_client.hgetall(user.id)
            # 将所有商品的 选中状态修改
            for key, value in carts_data.items():
                sku_id = int(key.decode())
                carts_dict = json.loads(value.decode())
                # 修改所有商品的 选中状态
                carts_dict['selected'] = selected
                carts_redis_client.hset(user.id, sku_id, json.dumps(carts_dict))
            return JsonResponse({'code': '0', 'errmsg': '全选购物车成功'})
        else:
            # 用户未登录，操作cookie购物车
            carts_str = request.COOKIES.get('carts')
            response = JsonResponse({'code': '0', 'errmsg': '全选购物车成功'})
            if carts_str is not None:
                carts_dict = CookieSecret.loads(carts_str)
                for sku_id in carts_dict:
                    carts_dict[sku_id]['selected'] = selected
                cookie_cart = CookieSecret.dumps(carts_dict)
                response.set_cookie('carts', cookie_cart, 24 * 30 * 3600)
            return response


class CartsView(View):
    """购物车管理"""

    # 删除购物车中某个商品
    def delete(self,request):
        user = request.user
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict['sku_id']
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist as e:
            settings.LOGGER.warning(e)
            return http.HttpResponseForbidden('商品不存在')

        if user.is_authenticated:
            try:
                redis_client = get_redis_connection("carts")
            except Exception as e:
                settings.LOGGER.warning(e)
                return http.HttpResponseForbidden('数据不存在')
            try:
                redis_client.hdel(user.id, sku.id)
            except Exception as e:
                settings.LOGGER.warning(e)
                return http.HttpResponseForbidden('商品不存在')
            return JsonResponse({'code': '0', 'errmsg': '删除购物车成功'})
        else:
            # 用户未登录，删除cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 转成明文
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            # 创建响应对象
            response = JsonResponse({'code': '0', 'errmsg': '删除购物车成功'})
            if sku_id in cart_dict:
                # 删除数据
                del cart_dict[sku_id]
                # 将字典转成密文
                cookie_cart_str = CookieSecret.dumps(cart_dict)
                # 响应结果并将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str, max_age=24 * 30 * 3600)
            return response

    # 修改、更新购物车信息
    def put(self,request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        user = request.user
        cookie_cart_str = ''
        if user.is_authenticated:
            # 用户已登录，修改redis购物车
            client = get_redis_connection("carts")
            new_data = {'count': count, 'selected': selected}
            client.hset(user.id, sku_id, json.dumps(new_data))
        else:
            # 用户未登录，修改cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            cookie_cart_str = CookieSecret.dumps(cart_dict)
        # 构建前端的数据
        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }
        response = JsonResponse({'code': '0', 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        if not user.is_authenticated:
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cookie_cart_str, max_age=24 * 30 * 3600)
        return response


    # 获取购物车信息
    def get(self, request):
        # 判断是否登陆，登陆从redis中找，不登陆从cookie中找
        user = request.user
        if user.is_authenticated:
            # 用户登陆了，从redis中找
            client = get_redis_connection("carts")
            carts_objs = client.hgetall(user.id)
            carts_dict = {}
            # 保持和cookie一样的形式，便于封装
            for key,value in carts_objs.items():
                sku_id = int(key.decode())
                sku_dict = json.loads(value.decode())
                carts_dict[sku_id]=sku_dict
        else:
            # 用户未登录，从cookie中找
            carts_objs = request.COOKIES.get('carts')
            if carts_objs:
                carts_dict = CookieSecret.loads(carts_objs)
            else:
                carts_dict = {}

        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
            'id': sku.id,
            'name': sku.name,
            'count': carts_dict.get(sku.id).get('count'),
            'selected': str(carts_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
            'default_image_url': sku.default_image.url,
            'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
            'amount': str(sku.price * carts_dict.get(sku.id).get('count')),
            })
        context = {
            'cart_skus':cart_skus,
        }
        # 渲染购物车页面
        return render(request, 'cart.html', context)

    def post(self, request):

        """添加购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 3.1 登录 使用redis存储
            carts_redis_client = get_redis_connection('carts')

            # 3.2 获取以前数据库的数据
            client_data = carts_redis_client.hgetall(user.id)

            # 如果商品已经存在就更新数据
            if str(sku_id).encode() in client_data:
                # 根据sku_id 取出商品
                child_dict = json.loads(client_data[str(sku_id).encode()].decode())
                #  个数累加
                child_dict['count'] += count
                # 更新数据
                carts_redis_client.hset(user.id, sku_id, json.dumps(child_dict))

            else:
                # 如果商品已经不存在--直接增加商品数据
                carts_redis_client.hset(user.id, sku_id, json.dumps({'count': count, 'selected': selected}))

            return JsonResponse({'code': '0', 'errmsg': '添加购物车成功'})
        else:
            # 用户未登录，操作cookie购物车
            cart_str = request.COOKIES.get('carts')
            # 如果用户操作过cookie购物车
            if cart_str:
                # 解密出明文
                cart_dict = CookieSecret.loads(cart_str)
            else:  # 用户从没有操作过cookie购物车
                cart_dict = {}

            # 判断要加入购物车的商品是否已经在购物车中,如有相同商品，累加求和，反之，直接赋值
            if sku_id in cart_dict:
                # 累加求和
                origin_count = cart_dict[sku_id]['count']
                count += origin_count
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            # 转成密文
            cookie_cart_str = CookieSecret.dumps(cart_dict)

            # 创建响应对象
            response = JsonResponse({'code': '0', 'errmsg': '添加购物车成功'})
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cookie_cart_str, max_age=24 * 30 * 3600)
            return response
